package com.qf.service.impl;

import com.qf.dao.UserDao;
import com.qf.dao.impl.UserDaoImpl;
import com.qf.pojo.PageBean;
import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.utils.DbUtils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author AzureSky_X
 * @Date 2021/1/5 20:30
 * @Version 1.0
 */
public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();

    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @Override
    public User login(String username, String password) {
        User user = null;

        try {
            //1.通过用户名查询数据库
            user = userDao.selectByUsername(username);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("用户名或密码错误");
        }

        //2.判断有没有用户
        if(null == user) {
            throw new RuntimeException("用户名不存在，请先注册");
        }
        //3.比对密码
        if(!user.getPassword().equals(password)) {
            throw new RuntimeException("用户名或密码错误");
        }

        //4.状态判断   intValue()：输出int数据
        if (user.getStatus().intValue()!=1){
            throw new RuntimeException("该用户状态非法！！");
        }

        return user;

    }

  // 显示所有用户

    @Override
    public List<User> showAllUser() {
        List<User> users=new ArrayList<>();
        List<User> temps=userDao.selectAllUser();
        if (temps!=null){
            users=temps;
        }
        return users;
    }
    //删除用户信息
    @Override
    public int deleteUser(int id) {
        int result=0;

        try {
            DbUtils.begin();
            result = userDao.deleteUser(id);
            DbUtils.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
    //修改用户信息
    @Override
    public int updateUser(User user) {

        try {
            DbUtils.begin();
            userDao.updateUser(user);
            DbUtils.commit();
        } catch (Exception e) {
            DbUtils.rollback();
            e.printStackTrace();
        }
        return 1;
    }
    //插入用户信息
    @Override
    public int insertUser(User user) {
        int result=0;
        try {
            DbUtils.begin();
            result =userDao.insertUser(user);
            DbUtils.commit();
        } catch (Exception e) {
            DbUtils.rollback();
            e.printStackTrace();
        }
        return result;
    }
    //根据id查询用户
    @Override
    public User selectUserById(int id) {
        User user=null;

        try {
            user= userDao.selectUserById(id);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("根据根据id查询用户出错！");
        }
        return user;
    }
    //分页查询用户信息
    @Override
    public PageBean<User> selectPage(String pageNo, Integer pageSize) {

        return null;
    }
}
